﻿using Lee.EF.Context;
using Lee.Models.Entities;
using Microsoft.EntityFrameworkCore; 

namespace EFCoreApp;

/// <summary>
/// 悲观并发控制
/// </summary>
public class EF_updlock2
{
    public void uplockTest()
    {
        string _currOwner = "test";//Console.ReadLine();//当前用户
        using var ctx = new MyDBContext();
        using var tx = ctx.Database.BeginTransaction();

        string sql3 = $@"select * from Biz_Coupons";
         
         


        string sql = $@"select * from Biz_Coupons  where Id=2";
        var cop = ctx.Biz_Coupons.FromSqlRaw(sql).Single();


        FormattableString sql2 = $@"select * from Biz_Coupons where Id=2";
        var cop2 = ctx.Set<Biz_Coupons>().FromSqlInterpolated(sql2).Single();//FromSqlInterpolated


        if (!string.IsNullOrEmpty(cop.Owner))
        {
            Console.WriteLine($"券被抢了");
        }
        else
        {
            cop.Owner = _currOwner;
            Thread.Sleep(5000);
            ctx.SaveChanges();
            Console.WriteLine($"恭喜{_currOwner}抢到券{cop.Id}了");
        }
        tx.Commit();
        Console.WriteLine($"EF_updlock end");
    }
}